<template>
  <view class='shop-cart'>
    <template v-if='cartslist.length > 0'>
      <uniNavBar
        title='购物车'
        :right-text='isNavBar ? "完成" : "编辑"'
        fixed='true'
        status-bar='true'
        @clickRight='isNavBar = !isNavBar'
      ></uniNavBar>

      <!-- 商品内容 -->
      <scroll-view class='shop-list' scroll-y>
        <view class='shop-item' v-for="carts in cartslist" :key="carts.cartid">
          <label class="radio" @click='handleItemSelection(carts)'>
            <radio value="" color="#FF3333" :checked="carts.checked"/><text></text>
          </label>
          <image class='shop-img' :src="carts.images"></image>
          <view class='shop-text'>
            <view class='shop-name'>{{carts.goodsName}}</view>
            <view class='shop-color'>{{carts.description}}</view>
            <view class='shop-price'>
              <view>￥{{carts.price}}</view>
              <view class='price-actions'>
                <QuantityControl
                  :value="Number(carts.quantity)"
                  @quantity-updated="updateCartQuantity(carts.cartid, $event)"
                />
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部 -->
      <view class='shop-foot'>
        <label class="radio foot-radio" @click="toggleSelectAll">
          <radio value="all" color="#FF3333" :checked="checkedAll"/><text>全选</text>
        </label>
        <template v-if='!isNavBar'>
          <view class='foot-total'>
            <view class='foot-count'>合计：
              <text class='foot-count'>￥{{totalprice}}</text>
            </view>
            <view class='foot-num' @click="toconfirm">
              结算
            </view>
          </view>
        </template>

        <template v-else>
          <view class='foot-total'>
            <view class='foot-count'></view>
            <view class='foot-num' style="background-color: red;" @click='deleteFn'>删除</view>
          </view>
        </template>
      </view>
    </template>

    <!-- 购物车为空 -->
    <template v-else>
      <uniNavBar title="购物车" status-bar="true" fixed="true"></uniNavBar>
      <view class='shop-else-list'>
        <text>购物车还是空的~快去加购吧~</text>
      </view>
    </template>
  </view>
</template>

<script>
import uniNavBar from '@/components/uni/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue';
import config from '@/config';
import QuantityControl from './QuantityControl.vue';

export default {
  components: {
    uniNavBar, // 注册组件
    QuantityControl
  },
  data() {
    return {
      isNavBar: false,
      cartslist: [], // 用于存储购物车数据
      checkedAll: false,
      selectedItems: [], // 用于存储选中的商品ID
      totalprice: 0,
    };
  },
  mounted() {
    this.fetchCarts(); // 页面加载时获取购物车数据
    uni.$on('cartUpdated', this.fetchCarts); // 监听购物车更新事件
  },
  beforeDestroy() {
    uni.$off('cartUpdated', this.fetchCarts); // 页面销毁时取消监听
  },
  methods: {
    // 更新商品数量并计算总价
    updateCartQuantity(cartId, newQuantity) {
        const item = this.cartslist.find(cart => cart.cartid === cartId);
        if (item) {
          item.quantity = newQuantity;
          uni.request({
            url: config.apiUrl + '/carts/' + cartId,
            method: 'PUT',
            data: { quantity: newQuantity, price: item.price },
            success: (res) => {
              if (res.statusCode === 200) {
                this.calculateTotalPrice();
              } else {
                console.error('Failed to update cart quantity:', res);
              }
            },
            fail: (err) => {
              console.error('Request failed:', err);
            }
          });
        }
      },
    toggleSelectAll() {
      this.checkedAll = !this.checkedAll;
      this.cartslist.forEach((item) => {
        item.checked = this.checkedAll;
      });
      this.calculateTotalPrice();
    },
    handleItemSelection(cart) {
      cart.checked = !cart.checked;
      this.calculateTotalPrice();
    },
    calculateTotalPrice() {
      this.totalprice = this.cartslist.reduce((total, item) => {
        if (item.checked) {
          const price = parseFloat(item.price);
          const quantity = parseInt(item.quantity, 10);
          if (!isNaN(price) && !isNaN(quantity)) {
            return total + (price * quantity);
          }
        }
        return total;
      }, 0);
      this.totalprice = parseFloat(this.totalprice.toFixed(2));
    },
    deleteFn() {
      const selectedIds = this.cartslist.filter(cart => cart.checked).map(cart => cart.cartid);
      uni.request({
        url: config.apiUrl + '/carts/batch',
        method: 'DELETE',
        data: selectedIds,
        success: (res) => {
          if (res.statusCode === 200) {
            this.cartslist = this.cartslist.filter(cart => !cart.checked);
            this.calculateTotalPrice();
            uni.$emit('cartUpdated'); // 发出购物车更新事件
          } else {
            console.error('Failed to delete carts:', res);
          }
        },
        fail: (err) => {
          console.error('Request failed:', err);
        }
      });
    },
    toconfirm() {
      if (this.totalprice === 0) {
        uni.showToast({
          title: '请至少选择一个商品',
          icon: 'none',
          duration: 2000,
        });
      } else {
        const selectedCarts = this.cartslist.filter(cart => cart.checked);
        const selectedIds = selectedCarts.map(cart => cart.cartid);

        // 先删除选中的购物车数据
        uni.request({
          url: config.apiUrl + '/carts/batch',
          method: 'DELETE',
          data: selectedIds,
          success: (res) => {
            if (res.statusCode === 200) {
              // 删除成功后存储选中数据并跳转至确认页面
              uni.setStorageSync('selectedCarts', {
                cartslist: selectedCarts,
                totalprice: this.totalprice
              });
              uni.navigateTo({
                url: '/pages/shopping/confirm'
              });
              // 更新界面数据
              this.cartslist = this.cartslist.filter(cart => !cart.checked);
              this.calculateTotalPrice();
              uni.$emit('cartUpdated'); // 发出购物车更新事件
            } else {
              console.error('Failed to delete carts:', res);
              uni.showToast({
                title: '删除购物车数据失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('Request failed:', err);
            uni.showToast({
              title: '网络错误',
              icon: 'none'
            });
          }
        });
      }
    },
     fetchCarts() {
       uni.request({
         url: config.apiUrl + '/carts/getbyuserid',
         method: 'GET',
         success: (res) => {
           if (res.statusCode === 200) {
             this.cartslist = res.data.map(cart => {
               return {
                 ...cart,
                 quantity: parseInt(cart.quantity, 10) // 确保数量是整数
               };
             });
             this.calculateTotalPrice();
           } else {
             console.error('Failed to fetch carts:', res);
           }
         },
         fail: (err) => {
           console.error('Request failed:', err);
         }
       });
     },
  }
};
</script>

<style scoped>
.shop-list {
  padding-bottom: 100rpx;
  background-color: #FFEFBA;
  height: calc(100vh - 100rpx); /* 确保 scroll-view 高度正确 */
  overflow: auto; /* 允许滚动 */
}
.shop-else-list {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #FFEFBA;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.shop-item {
  display: flex;
  padding: 25px;
  background-color: #EAD48E;
  margin: 15rpx;
  margin-top: 0;
  border-radius: 25px 25rpx;
}
.shop-img {
  width: 200rpx;
  height: 200rpx;
  margin-right: 15rpx;
  border-radius: 15px;
}
.shop-text {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.shop-name {
  font-size: 30rpx;
}
.shop-color {
  font-size: 24rpx;
  margin-top: 15rpx;
}
.shop-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.price-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.shop-foot {
  border-top: 2rpx solid #f7f7f7;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  z-index: 1000; /* 确保在其他内容之上 */
  padding: 0 20rpx; /* 添加左右两侧内边距 */
}
.foot-radio {
  padding-left: 20rpx;
}
.foot-total {
  display: flex;
  align-items: center;
}
.foot-count {
  line-height: 100rpx;
  padding: 0 20rpx;
}
.foot-num {
  background-color: #EACD6F;
  color: #ffffff;
  padding: 0 60rpx;
  line-height: 100rpx;
  width: 150rpx;
  text-align: center;
  cursor: pointer;
}
</style>
